#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
桌面版视频拆分工具
独立的命令行/GUI视频拆分工具，不依赖Android环境
支持Windows、Linux、macOS等桌面平台
"""

import os
import sys
import argparse
import json
from pathlib import Path
from datetime import timedelta
from typing import List, Tuple, Optional

# 导入视频处理工具
from video_utils import VideoInfo, VideoSplitter, format_duration, validate_split_points

# GUI相关导入（可选）
try:
    import tkinter as tk
    from tkinter import filedialog, messagebox, ttk
    GUI_AVAILABLE = True
except ImportError:
    GUI_AVAILABLE = False
    print("GUI不可用，仅支持命令行模式")


class DesktopVideoSplitter:
    """桌面版视频拆分器"""
    
    def __init__(self):
        self.video_info = None
        self.video_splitter = VideoSplitter()
        self.split_points = []
        self.output_dir = None
        
    def load_video(self, video_path: str) -> bool:
        """加载视频文件"""
        try:
            if not os.path.exists(video_path):
                print(f"错误：视频文件不存在 - {video_path}")
                return False
                
            self.video_info = VideoInfo(video_path)
            if not self.video_info.is_valid():
                print(f"错误：无法读取视频信息 - {video_path}")
                return False
                
            print(f"视频加载成功：")
            print(f"  文件：{video_path}")
            print(f"  分辨率：{self.video_info.get_resolution_string()}")
            print(f"  时长：{self.video_info.get_duration_string()}")
            print(f"  格式：{self.video_info.format_name}")
            print(f"  大小：{self.video_info.get_file_size_string()}")
            return True
            
        except Exception as e:
            print(f"加载视频失败：{e}")
            return False
    
    def add_split_point(self, time_seconds: float) -> bool:
        """添加拆分点"""
        if not self.video_info:
            print("错误：请先加载视频文件")
            return False
            
        if time_seconds < 0 or time_seconds >= self.video_info.duration:
            print(f"错误：拆分时间点无效 ({time_seconds}s)，应在 0 到 {self.video_info.duration}s 之间")
            return False
            
        # 检查是否已存在相近的拆分点
        for existing_time in self.split_points:
            if abs(existing_time - time_seconds) < 1.0:  # 1秒内认为是重复
                print(f"警告：拆分点 {time_seconds}s 与现有拆分点 {existing_time}s 过于接近")
                return False
                
        self.split_points.append(time_seconds)
        self.split_points.sort()
        print(f"添加拆分点：{format_duration(time_seconds)}")
        return True
    
    def remove_split_point(self, time_seconds: float) -> bool:
        """移除拆分点"""
        if time_seconds in self.split_points:
            self.split_points.remove(time_seconds)
            print(f"移除拆分点：{format_duration(time_seconds)}")
            return True
        else:
            print(f"错误：拆分点 {time_seconds}s 不存在")
            return False
    
    def list_split_points(self):
        """列出所有拆分点"""
        if not self.split_points:
            print("当前没有拆分点")
            return
            
        print("当前拆分点：")
        for i, time_seconds in enumerate(self.split_points, 1):
            print(f"  {i}. {format_duration(time_seconds)}")
    
    def set_output_directory(self, output_dir: str) -> bool:
        """设置输出目录"""
        try:
            output_path = Path(output_dir)
            output_path.mkdir(parents=True, exist_ok=True)
            self.output_dir = str(output_path.absolute())
            print(f"输出目录设置为：{self.output_dir}")
            return True
        except Exception as e:
            print(f"设置输出目录失败：{e}")
            return False
    
    def split_video(self, progress_callback=None) -> bool:
        """执行视频拆分"""
        if not self.video_info:
            print("错误：请先加载视频文件")
            return False
            
        if not self.split_points:
            print("错误：请至少添加一个拆分点")
            return False
            
        # 验证拆分点
        if not validate_split_points(self.split_points, self.video_info.duration):
            print("错误：拆分点验证失败")
            return False
            
        # 设置默认输出目录
        if not self.output_dir:
            video_dir = os.path.dirname(self.video_info.file_path)
            self.output_dir = os.path.join(video_dir, "split_output")
            os.makedirs(self.output_dir, exist_ok=True)
            print(f"使用默认输出目录：{self.output_dir}")
        
        try:
            print("开始拆分视频...")
            
            def default_progress_callback(current, total, message):
                percent = (current / total) * 100 if total > 0 else 0
                print(f"\r进度：{percent:.1f}% - {message}", end="", flush=True)
            
            callback = progress_callback or default_progress_callback
            
            success = self.video_splitter.split_video(
                input_file=self.video_info.file_path,
                split_points=self.split_points,
                output_dir=self.output_dir,
                progress_callback=callback
            )
            
            print()  # 换行
            
            if success:
                print("视频拆分完成！")
                print(f"输出文件保存在：{self.output_dir}")
                return True
            else:
                print("视频拆分失败")
                return False
                
        except Exception as e:
            print(f"拆分过程中发生错误：{e}")
            return False
    
    def save_project(self, project_file: str) -> bool:
        """保存项目配置"""
        try:
            project_data = {
                'video_path': self.video_info.file_path if self.video_info else None,
                'split_points': self.split_points,
                'output_dir': self.output_dir
            }
            
            with open(project_file, 'w', encoding='utf-8') as f:
                json.dump(project_data, f, indent=2, ensure_ascii=False)
            
            print(f"项目已保存到：{project_file}")
            return True
            
        except Exception as e:
            print(f"保存项目失败：{e}")
            return False
    
    def load_project(self, project_file: str) -> bool:
        """加载项目配置"""
        try:
            if not os.path.exists(project_file):
                print(f"错误：项目文件不存在 - {project_file}")
                return False
            
            with open(project_file, 'r', encoding='utf-8') as f:
                project_data = json.load(f)
            
            # 加载视频
            if project_data.get('video_path'):
                if not self.load_video(project_data['video_path']):
                    print("警告：无法加载项目中的视频文件")
            
            # 加载拆分点
            self.split_points = project_data.get('split_points', [])
            
            # 加载输出目录
            if project_data.get('output_dir'):
                self.output_dir = project_data['output_dir']
            
            print(f"项目已从 {project_file} 加载")
            self.list_split_points()
            return True
            
        except Exception as e:
            print(f"加载项目失败：{e}")
            return False


class DesktopVideoSplitterGUI:
    """桌面版视频拆分器GUI界面"""
    
    def __init__(self):
        if not GUI_AVAILABLE:
            raise ImportError("GUI组件不可用")
            
        self.splitter = DesktopVideoSplitter()
        self.root = tk.Tk()
        self.root.title("桌面视频拆分工具")
        self.root.geometry("600x500")
        
        # 移除了视频播放相关变量
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置用户界面"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 文件选择区域
        file_frame = ttk.LabelFrame(main_frame, text="视频文件", padding="5")
        file_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        self.file_label = ttk.Label(file_frame, text="未选择文件")
        self.file_label.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(file_frame, text="选择视频", command=self.select_video).grid(row=0, column=1)
        
        # 视频信息显示
        self.info_text = tk.Text(file_frame, height=3, width=60)
        self.info_text.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(10, 0))
        
        # 移除了视频播放器区域，简化为基于输入的拆分点管理
        
        # 拆分点管理区域
        split_frame = ttk.LabelFrame(main_frame, text="拆分点管理", padding="5")
        split_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 添加拆分点
        add_frame = ttk.Frame(split_frame)
        add_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
        
        ttk.Label(add_frame, text="时间点 (秒):").grid(row=0, column=0, padx=(0, 5))
        self.time_entry = ttk.Entry(add_frame, width=10)
        self.time_entry.grid(row=0, column=1, padx=(0, 5))
        ttk.Button(add_frame, text="添加", command=self.add_split_point).grid(row=0, column=2)
        
        # 拆分点列表
        self.split_listbox = tk.Listbox(split_frame, height=6)
        self.split_listbox.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(5, 0))
        
        ttk.Button(split_frame, text="删除选中", command=self.remove_split_point).grid(row=2, column=0, pady=(5, 0))
        
        # 输出设置区域
        output_frame = ttk.LabelFrame(main_frame, text="输出设置", padding="5")
        output_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        self.output_label = ttk.Label(output_frame, text="输出目录：未设置")
        self.output_label.grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        
        ttk.Button(output_frame, text="选择目录", command=self.select_output_dir).grid(row=0, column=1)
        
        # 操作按钮区域
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=4, column=0, columnspan=2, pady=(0, 10))
        
        ttk.Button(button_frame, text="开始拆分", command=self.start_split).grid(row=0, column=0, padx=(0, 5))
        ttk.Button(button_frame, text="保存项目", command=self.save_project).grid(row=0, column=1, padx=(0, 5))
        ttk.Button(button_frame, text="加载项目", command=self.load_project).grid(row=0, column=2)
        
        # 进度条
        self.progress = ttk.Progressbar(main_frame, mode='determinate')
        self.progress.grid(row=5, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
        
        # 状态标签
        self.status_label = ttk.Label(main_frame, text="就绪")
        self.status_label.grid(row=6, column=0, columnspan=2)
        
        # 配置网格权重
        main_frame.columnconfigure(0, weight=1)
        file_frame.columnconfigure(0, weight=1)
        split_frame.columnconfigure(0, weight=1)
        output_frame.columnconfigure(0, weight=1)
    
    def select_video(self):
        """选择视频文件"""
        file_path = filedialog.askopenfilename(
            title="选择视频文件",
            filetypes=[
                ("视频文件", "*.mp4 *.avi *.mov *.mkv *.wmv *.flv *.webm"),
                ("所有文件", "*.*")
            ]
        )
        
        if file_path:
            if self.splitter.load_video(file_path):
                self.file_label.config(text=os.path.basename(file_path))
                self.update_video_info()
                self.status_label.config(text="视频加载成功")
            else:
                messagebox.showerror("错误", "无法加载视频文件")
    
    def update_video_info(self):
        """更新视频信息显示"""
        if self.splitter.video_info:
            info = self.splitter.video_info
            info_text = f"分辨率：{info.get_resolution_string()}\n"
            info_text += f"时长：{info.get_duration_string()}\n"
            info_text += f"格式：{info.format_name}\n"
            info_text += f"大小：{info.get_file_size_string()}"
            
            self.info_text.delete(1.0, tk.END)
            self.info_text.insert(1.0, info_text)
    
    def add_split_point(self):
        """添加拆分点"""
        try:
            time_seconds = float(self.time_entry.get())
            if self.splitter.add_split_point(time_seconds):
                self.update_split_list()
                self.time_entry.delete(0, tk.END)
                self.status_label.config(text=f"添加拆分点：{format_duration(time_seconds)}")
            else:
                messagebox.showerror("错误", "无法添加拆分点")
        except ValueError:
            messagebox.showerror("错误", "请输入有效的时间（秒）")
    
    def remove_split_point(self):
        """删除选中的拆分点"""
        selection = self.split_listbox.curselection()
        if selection:
            index = selection[0]
            if index < len(self.splitter.split_points):
                time_seconds = self.splitter.split_points[index]
                if self.splitter.remove_split_point(time_seconds):
                    self.update_split_list()
                    self.status_label.config(text=f"删除拆分点：{format_duration(time_seconds)}")
    
    def update_split_list(self):
        """更新拆分点列表显示"""
        self.split_listbox.delete(0, tk.END)
        for time_seconds in self.splitter.split_points:
            self.split_listbox.insert(tk.END, f"{format_duration(time_seconds)}")
    
    # 移除了视频播放器初始化方法
    
    # 移除了显示帧方法
    
    # 移除了所有视频播放控制方法
    
    # 移除了进度条和时间相关的方法
    
    def select_output_dir(self):
        """选择输出目录"""
        dir_path = filedialog.askdirectory(title="选择输出目录")
        if dir_path:
            if self.splitter.set_output_directory(dir_path):
                self.output_label.config(text=f"输出目录：{os.path.basename(dir_path)}")
                self.status_label.config(text="输出目录设置成功")
    
    def start_split(self):
        """开始拆分视频"""
        if not self.splitter.video_info:
            messagebox.showerror("错误", "请先选择视频文件")
            return
        
        if not self.splitter.split_points:
            messagebox.showerror("错误", "请至少添加一个拆分点")
            return
        
        # 在新线程中执行拆分
        import threading
        
        def progress_callback(current, total, message):
            percent = (current / total) * 100 if total > 0 else 0
            self.root.after(0, lambda: self.progress.config(value=percent))
            self.root.after(0, lambda: self.status_label.config(text=message))
        
        def split_thread():
            try:
                success = self.splitter.split_video(progress_callback)
                if success:
                    self.root.after(0, lambda: messagebox.showinfo("完成", "视频拆分完成！"))
                    self.root.after(0, lambda: self.status_label.config(text="拆分完成"))
                else:
                    self.root.after(0, lambda: messagebox.showerror("错误", "视频拆分失败"))
                    self.root.after(0, lambda: self.status_label.config(text="拆分失败"))
            except Exception as e:
                self.root.after(0, lambda: messagebox.showerror("错误", f"拆分过程中发生错误：{e}"))
            finally:
                self.root.after(0, lambda: self.progress.config(value=0))
        
        self.status_label.config(text="正在拆分视频...")
        threading.Thread(target=split_thread, daemon=True).start()
    
    def save_project(self):
        """保存项目"""
        file_path = filedialog.asksaveasfilename(
            title="保存项目",
            defaultextension=".json",
            filetypes=[("项目文件", "*.json"), ("所有文件", "*.*")]
        )
        
        if file_path:
            if self.splitter.save_project(file_path):
                self.status_label.config(text="项目保存成功")
            else:
                messagebox.showerror("错误", "项目保存失败")
    
    def load_project(self):
        """加载项目"""
        file_path = filedialog.askopenfilename(
            title="加载项目",
            filetypes=[("项目文件", "*.json"), ("所有文件", "*.*")]
        )
        
        if file_path:
            if self.splitter.load_project(file_path):
                # 更新界面
                if self.splitter.video_info:
                    self.file_label.config(text=os.path.basename(self.splitter.video_info.file_path))
                    self.update_video_info()
                
                self.update_split_list()
                
                if self.splitter.output_dir:
                    self.output_label.config(text=f"输出目录：{os.path.basename(self.splitter.output_dir)}")
                
                self.status_label.config(text="项目加载成功")
            else:
                messagebox.showerror("错误", "项目加载失败")
    
    def run(self):
        """运行GUI"""
        self.root.mainloop()


def parse_time(time_str: str) -> float:
    """解析时间字符串为秒数"""
    try:
        # 支持格式：123.45 或 1:23.45 或 1:23:45.67
        if ':' in time_str:
            parts = time_str.split(':')
            if len(parts) == 2:  # mm:ss
                minutes, seconds = parts
                return int(minutes) * 60 + float(seconds)
            elif len(parts) == 3:  # hh:mm:ss
                hours, minutes, seconds = parts
                return int(hours) * 3600 + int(minutes) * 60 + float(seconds)
        else:
            return float(time_str)
    except ValueError:
        raise ValueError(f"无效的时间格式：{time_str}")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="桌面版视频拆分工具")
    parser.add_argument('--gui', action='store_true', help='启动GUI界面')
    parser.add_argument('--video', '-v', help='视频文件路径')
    parser.add_argument('--splits', '-s', nargs='+', help='拆分时间点（秒或时:分:秒格式）')
    parser.add_argument('--output', '-o', help='输出目录')
    parser.add_argument('--project', '-p', help='项目文件路径')
    parser.add_argument('--save-project', help='保存项目到指定文件')
    
    args = parser.parse_args()
    
    # GUI模式
    if args.gui:
        if not GUI_AVAILABLE:
            print("错误：GUI组件不可用，请安装tkinter")
            return 1
        
        try:
            app = DesktopVideoSplitterGUI()
            app.run()
            return 0
        except Exception as e:
            print(f"GUI启动失败：{e}")
            return 1
    
    # 命令行模式
    splitter = DesktopVideoSplitter()
    
    # 加载项目文件
    if args.project:
        if not splitter.load_project(args.project):
            return 1
    
    # 加载视频文件
    if args.video:
        if not splitter.load_video(args.video):
            return 1
    
    # 添加拆分点
    if args.splits:
        for split_str in args.splits:
            try:
                time_seconds = parse_time(split_str)
                splitter.add_split_point(time_seconds)
            except ValueError as e:
                print(f"错误：{e}")
                return 1
    
    # 设置输出目录
    if args.output:
        if not splitter.set_output_directory(args.output):
            return 1
    
    # 保存项目
    if args.save_project:
        if not splitter.save_project(args.save_project):
            return 1
        return 0
    
    # 如果没有指定视频文件，进入交互模式
    if not splitter.video_info:
        print("桌面视频拆分工具 - 交互模式")
        print("输入 'help' 查看帮助")
        
        while True:
            try:
                command = input("\n> ").strip().split()
                if not command:
                    continue
                
                cmd = command[0].lower()
                
                if cmd == 'help':
                    print("可用命令：")
                    print("  load <video_path>     - 加载视频文件")
                    print("  add <time>            - 添加拆分点（秒或时:分:秒）")
                    print("  remove <time>         - 删除拆分点")
                    print("  list                  - 列出拆分点")
                    print("  output <dir>          - 设置输出目录")
                    print("  split                 - 开始拆分")
                    print("  save <project_file>   - 保存项目")
                    print("  load_project <file>   - 加载项目")
                    print("  quit                  - 退出")
                
                elif cmd == 'load' and len(command) > 1:
                    splitter.load_video(' '.join(command[1:]))
                
                elif cmd == 'add' and len(command) > 1:
                    try:
                        time_seconds = parse_time(command[1])
                        splitter.add_split_point(time_seconds)
                    except ValueError as e:
                        print(f"错误：{e}")
                
                elif cmd == 'remove' and len(command) > 1:
                    try:
                        time_seconds = parse_time(command[1])
                        splitter.remove_split_point(time_seconds)
                    except ValueError as e:
                        print(f"错误：{e}")
                
                elif cmd == 'list':
                    splitter.list_split_points()
                
                elif cmd == 'output' and len(command) > 1:
                    splitter.set_output_directory(' '.join(command[1:]))
                
                elif cmd == 'split':
                    splitter.split_video()
                
                elif cmd == 'save' and len(command) > 1:
                    splitter.save_project(' '.join(command[1:]))
                
                elif cmd == 'load_project' and len(command) > 1:
                    splitter.load_project(' '.join(command[1:]))
                
                elif cmd in ['quit', 'exit', 'q']:
                    break
                
                else:
                    print("未知命令，输入 'help' 查看帮助")
                    
            except KeyboardInterrupt:
                print("\n再见！")
                break
            except EOFError:
                break
        
        return 0
    
    # 如果有视频文件但没有拆分点，提示用户
    if not splitter.split_points:
        print("\n请添加拆分点后再执行拆分")
        print("使用 --splits 参数指定拆分点，或使用 --gui 启动图形界面")
        return 1
    
    # 执行拆分
    if splitter.split_video():
        return 0
    else:
        return 1


if __name__ == '__main__':
    sys.exit(main())